<template>
  <div>
    <a-card>
      <a-form layout="inline">
        <a-form-item>
          <a-input
            style="width:280px;
                font-size:14px;
                font-family:Microsoft YaHei;
                color:rgba(190,194,201,1)"
            placeholder="请输入公式名称或者最后修改人名称"
            v-model="formulaQueryCondition.queryText"
          >
            <a-icon slot="suffix" type="search" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-select v-model="formulaQueryCondition.enabled" style="width:240px;" placeholder="状态">
            <a-select-option
              :value="item.value"
              :key="item.value"
              v-for="item in [{label:'启用',value:'Y'},{label:'不启用',value:'N'}]"
            >{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button
            style="margin-left: 30px;"
            @click="handleFormulaSearch"
            icon="search"
            type="primary"
          >查询</a-button>
          <a-button
            style="margin-left: 30px;"
            @click="()=>{this.formulaQueryCondition={};this.handleFormulaSearch()}"
            icon="sync"
          >重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card style="margin-top: 22px;">
      <a-button
        style="margin-bottom: 12px;"
        @click="handleFormulaCreate"
        type="primary"
        icon="plus"
      >新增</a-button>
      <a-table
        rowKey="id"
        :data-source="formulas"
        :pagination="formulaPagination"
        @change="handleFormulaPageChange"
        :loading="formulaLoading"
        :columns="[
          {title:'公式名称',dataIndex:'name',key:'name'},
          {title:'公式描述',dataIndex:'description',key:'description'},
          {title:'最后修改日期',dataIndex:'lastUpdateTime',key:'lastUpdateTime'},
          {title:'最后修改人',dataIndex:'lastUpdateByName',key:'lastUpdateByName'},
          {title:'绑定规则数',dataIndex:'ruleCount',key:'ruleCount',scopedSlots:{customRender:'ruleCount'}},
          {title:'状态',dataIndex:'enabled',key:'enabled',scopedSlots:{customRender:'enabled'}},
          {title:'操作', dataIndex:'options', key:'options', align:'center', scopedSlots:{customRender:'options'}, width:'240px' },
        ]"
      >
        <template slot="ruleCount" slot-scope="text,record">
          <a-button type="link" @click="()=>handleShowRule(record)">{{ text?text:0 }}</a-button>
        </template>
        <template slot="enabled" slot-scope="text">{{ text==='Y'?'启用':'不启用' }}</template>
        <template slot="options" slot-scope="text,record">
          <a-button
            size="small"
            style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;
            "
            type="link"
            @click="handleShowFormula(record)"
          >详情</a-button>
          <a-button
            size="small"
            style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;
            "
            type="link"
            @click="handleEditFormula(record)"
          >编辑</a-button>
          <a-button
            size="small"
            style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;
            "
            type="link"
            @click="handleCopyFormula(record)"
          >复制</a-button>

          <a-popconfirm
            title="确认删除?"
            ok-text="是"
            cancel-text="否"
            @confirm="()=>handleDeleteFormula(record)"
          >
            <a-button
              size="small"
              style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;
              color:#ff4d4f;
            "
              type="link"
            >删除</a-button>
          </a-popconfirm>
          <a-button
            v-loading="record.enabledLoading"
            v-if="record.enabled==='Y'"
            size="small"
            style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;
              color:#ff4d4f;
            "
            type="link"
            @click="handleDisableFormula(record)"
          >禁用</a-button>
          <a-button
            v-loading="record.enabledLoading"
            type="link"
            size="small"
            style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
            @click="handleDisableFormula(record)"
            v-else
          >启用</a-button>
        </template>
      </a-table>
    </a-card>

    <a-modal
      ok-text="编辑"
      @ok="handleShow2Edit"
      v-model="formulaShowVisible"
      width="688px"
      title="公式详情"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="公式名称">{{ formulaShow.name }}</a-descriptions-item>
        <a-descriptions-item label="公式描述">{{ formulaShow.description }}</a-descriptions-item>
        <a-descriptions-item label="总记录查询">
          <div :key="line.id" v-for="line in formulaShow.lines">
            <div v-show="line.type==='score'">{{ line.sql1 }}</div>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="异常记录查询">
          <div :key="line.id" v-for="line in formulaShow.lines">
            <div v-show="line.type==='error_result'">{{ line.sql1 }}</div>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="得分计算">
          <div :key="line.id" v-for="line in formulaShow.lines">
            <div v-show="line.type==='score'">{{ line.sql2 }}</div>
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <a-modal
      :bodyStyle="{'overflow-y':'scroll','max-height':'700px'}"
      v-model="showRuleVisible"
      :footer="null"
      width="688px"
      title="使用规则"
    >
      <a-table
        rowKey="id"
        :pagination="false"
        :data-source="showRules"
        :columns="[
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            scopedSlots: { customRender: 'index' }
          },
          {
            title: '规则名称',
            dataIndex: 'name',
            key: 'name'
          },
          {
            title: '规则类型',
            dataIndex: 'type',
            key: 'type',
            scopedSlots: { customRender: 'type' }
          },
          {
            title: '规则状态',
            dataIndex: 'enabled',
            key: 'enabled',
            scopedSlots: { customRender: 'enabled' }
          }
        ]"
      >
        <template slot="index" slot-scope="text,record,index">{{ index+1 }}</template>
        <template slot="enabled" slot-scope="text,record">
          {{ text==='Y'?'启用':'不启用' }}
          <a-popconfirm placement="topLeft" ok-text="确认" cancel-text="取消" @confirm="requestRemoveFormula(record)">
            <template slot="title">
              <p>解绑</p>
              <p>确认将该公式解除绑定？解除后对应规则状态将置为禁用。</p>
            </template>
            <!-- <a-button @click="handleRemoveRule(record)">解绑</a-button> -->
            <a-button type="link">解绑</a-button>
          </a-popconfirm>
        </template>
        <template slot="type" slot-scope="text">{{ ruleTypeLabel[text] }}</template>
      </a-table>
    </a-modal>
    <a-modal
      width="1000px"
      :bodyStyle="{'overflow-y':'scroll','height':'700px'}"
      v-model="formulaEditVisible"
      :title="formulaEdit.id?'编辑>'+formulaEdit.name:'新增'"
    >
      <template slot="footer">
        <a-button key="back" @click="()=>formulaEditVisible=false">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="formulaEditLoading"
          @click="doSaveFormula"
        >确定</a-button>
      </template>
      <a-form-model
        ref="formulaEditForm"
        :labelCol="{span:4}"
        :wrapperCol="{span:14}"
        :rules="formulaEditValidateRule"
        :model="formulaEdit"
      >
        <a-form-model-item prop="name" label="公式名称">
          <a-input v-model="formulaEdit.name"></a-input>
        </a-form-model-item>
        <a-form-model-item prop="description" label="公式描述">
          <a-textarea v-model="formulaEdit.description"></a-textarea>
        </a-form-model-item>
        <a-form-model-item prop="allCountSql" label="总记录查询">
          <a-textarea v-model="formulaEdit.allCountSql"></a-textarea>
        </a-form-model-item>
        <a-form-model-item prop="passCountSql" label="得分记录查询">
          <a-textarea v-model="formulaEdit.passCountSql"></a-textarea>
        </a-form-model-item>
        <a-form-model-item prop="errDataSql" label="异常记录查询">
          <a-textarea v-model="formulaEdit.errDataSql"></a-textarea>
        </a-form-model-item>
        <a-form-model-item label="参数">
          <a-row>
            <a-button @click="generatorParam">确认参数</a-button>
            <div
              style="width:275px;
              height:12px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;
              color:rgba(203,146,80,1);"
            >
              参数将用于规则配置中，若参数有误请修改查询语句
            </div>
          </a-row>
          <br/>
          <a-row
            style="
            background:rgba(249,251,253,1);
            border-radius:4px;">
            <a-tag :key="tag" color="blue" v-for="tag in params">{{ tag }}</a-tag>
          </a-row>
        </a-form-model-item>
        <a-form-model-item prop="enabled" label="状态">
          <a-switch
            style="width: 70px;"
            checkedChildren=" 启用"
            unCheckedChildren="不启用"
            :checked="formulaEdit.enabled==='Y'"
            @change="checked=>formulaEdit.enabled = checked?'Y':'N'"
          ></a-switch>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { queryFormulaWithLines, saveFormula, deleteFormula, setFormulaEnable } from '@/api/formula'
import { listRules, removeFormula } from '@/api/rule'
import { deepCopy } from '@/utils/util'
export default {
  name: 'Formula',
  data () {
    return {
      ruleTypeLabel: {
        1: '一致性',
        2: '完整性',
        3: '及时性',
        4: '规范性'
      },
      formulaQueryCondition: {},
      formulaEdit: {
        name: null,
        description: null,
        allCountSql: null,
        passCountSql: null,
        errDataSql: null,
        enabled: 'Y',
        params: []
      },
      formulaEditValidateRule: {
        name: [{ required: true, message: '请输入公式名' }],
        allCountSql: [{ required: true, message: '请输入总记录查询sql' }],
        passCountSql: [{ required: true, message: '请输入得分记录查询sql' }],
        errDataSql: [{ required: true, message: '请输入异常记录查询sql' }]
      },
      formulaEditLoading: false,
      formulaEditVisible: false,
      formulas: [],
      formulaPagination: {
        showTotal: total => `共 ${total} 条记录`,
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true
      },
      formulaLoading: false,
      formulaShowVisible: false,
      formulaShow: {},
      showRules: [],
      showRuleVisible: false,
      params: []
    }
  },
  created () {
    this.handleFormulaSearch()
  },
  activated: function () {
    const toAdd = this.$router.params.add
    if (toAdd) {
      this.handleFormulaCreate()
    }
  },
  methods: {
    /**
     * 生成参数
     */
    generatorParam: function () {
      const reg = /(?<=\$\{bind\.).*?(?=})/gi
      const reg2 = /(?<=#\{bind\.).*?(?=})/gi
      const sql1 = this.formulaEdit.allCountSql
      const tags = []
      let matchResult = sql1.match(reg)
      if (matchResult) {
        matchResult.forEach(e => {
          if (!tags.includes('bind.' + e)) tags.push('bind.' + e)
        })
      }
      matchResult = sql1.match(reg2)
      if (matchResult) {
        matchResult.forEach(e => {
          if (!tags.includes('bind.' + e)) tags.push('bind.' + e)
        })
      }
      const sql2 = this.formulaEdit.passCountSql
      matchResult = sql2.match(reg)
      if (matchResult) {
        matchResult.forEach(e => {
          if (!tags.includes('bind.' + e)) tags.push('bind.' + e)
        })
      }
      matchResult = sql2.match(reg2)
      if (matchResult) {
        matchResult.forEach(e => {
          if (!tags.includes('bind.' + e)) tags.push('bind.' + e)
        })
      }
      const sql3 = this.formulaEdit.errDataSql
      matchResult = sql3.match(reg)
      if (matchResult) {
        matchResult.forEach(e => {
          if (!tags.includes('bind.' + e)) tags.push('bind.' + e)
        })
      }
      matchResult = sql3.match(reg2)
      if (matchResult) {
        matchResult.forEach(e => {
          if (!tags.includes('bind.' + e)) tags.push('bind.' + e)
        })
      }
      this.params = []
      this.params.push(...tags)
    },
    handleRemoveRule (tRule) {
      console.log(tRule)
      const that = this
      this.$confirm({
        title: '解绑',
        content: '确认将该公式从' + tRule.name + '规则下解除绑定？解除后对应规则状态将置为禁用。',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          return new Promise((resolve, reject) => {
            const res = that.requestRemoveFormula(resolve, reject, tRule)
            return res
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    requestRemoveFormula (tRule) {
      console.log(tRule)
      const that = this
      removeFormula({ id: tRule.id }).then(res => {
        if (res.code !== 200) {
          // reject()
          that.$message.error(res.message)
          return
        }
        // resolve() // 接口响应成功，返回 promise 时 resolve 后自动关闭询问弹窗
        that.showRules.splice(
          that.showRules.findIndex(item => item.id === tRule.id),
          1
        )
        that.formulas.forEach(e => {
          if (e.id === tRule.formulaId) {
            e.ruleCount--
          }
        })
      }).catch((err) => {
        console.log(err)
        // reject()
      })
    },
    doFormulaQuery: function () {
      this.formulaLoading = true
      queryFormulaWithLines(this.formulaQueryCondition, this.formulaPagination.current, this.formulaPagination.pageSize)
        .then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            return
          }
          this.formulaPagination.total = res.data.total
          this.formulas = res.data.rows
          this.formulaPagination.current = res.data.pageNum
          this.formulaPagination.pageSize = res.data.pageSize
        })
        .finally(() => {
          this.formulaLoading = false
        })
    },
    handleFormulaCreate: function () {
      this.formulaEdit = {
        enabled: 'Y'
      }
      this.formulaEditVisible = true
    },
    handleFormulaPageChange: function (pagination) {
      this.formulaPagination = pagination
      this.doFormulaQuery()
    },
    handleFormulaSearch: function () {
      this.formulaPagination.current = 1
      this.doFormulaQuery()
    },
    /**
     * 展示绑定的规则
     */
    handleShowRule: function (record) {
      listRules({ formulaId: record.id }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
        }
        this.showRules = res.data
        this.showRuleVisible = true
      })
    },
    handleShowFormula: function (record) {
      this.formulaShow = deepCopy(record)
      this.formulaShowVisible = true
    },
    handleShow2Edit: function () {
      this.formulaShowVisible = false
      this.handleEditFormula(this.formulaShow)
    },
    handleEditFormula: function (record) {
      const source = deepCopy(record)
      if (source.lines) {
        source.lines.forEach(e => {
          if (e.type === 'error_result') {
            source.errDataSql = e.sql1
          } else if (e.type === 'score') {
            source.allCountSql = e.sql1
            source.passCountSql = e.sql2
          }
        })
      }
      this.formulaEdit = source
      this.formulaEditVisible = true
    },
    doSaveFormula: function () {
      this.$refs.formulaEditForm.validate(valid => {
        if (!valid) {
          this.$message('参数有误')
          return
        }
        this.formulaEditLoading = true
        this.formulaEdit.matchParamFromSql = true
        saveFormula(this.formulaEdit)
          .then(res => {
            if (res.code !== 200) {
              this.$message.error(res.message)
              return
            }
            this.handleFormulaSearch()
            this.formulaEditVisible = false
          })
          .finally(() => {
            this.formulaEditLoading = false
          })
      })
    },
    handleCopyFormula: function (record) {
      const source = deepCopy(record)
      source.id = null
      this.handleEditFormula(source)
    },
    handleDeleteFormula: function (record) {
      deleteFormula(record.id).then(res => {
        if (res.code === 200) {
          const list = []
          this.formulas.forEach(e => {
            if (e.id !== record.id) {
              list.push(e)
            }
          })
          this.formulas = list
        }
      })
    },
    handleDisableFormula: function (record) {
      const data = { enabled: record.enabled === 'Y' ? 'N' : 'Y', id: record.id }
      this.$set(record, 'enabledLoading', true)
      setFormulaEnable(data)
        .then(res => {
          if (res.code === 200) {
            const list = []
            this.formulas.forEach(e => {
              if (e.id !== record.id) {
                list.push(e)
              } else {
                e.enabled = res.data.enabled
                e.lastUpdateByName = res.data.lastUpdateByName
                e.lastUpdateBy = res.data.lastUpdateBy
                e.lastUpdateTime = res.data.lastUpdateTime
                list.push(e)
              }
            })
            this.formulas = list
          }
        })
        .finally(() => {
          this.$set(record, 'enabledLoading', false)
        })
    }
  }
}

</script>
